import React, { useState,useRef,useEffect } from 'react';  
import { Steps, Card, Row, Col,Form,Button,Input,Modal,Select,List,Table, message,Upload,Tooltip,Tabs} from 'antd';
import { UploadOutlined } from '@ant-design/icons';   
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { useNavigate  } from 'react-router-dom';
import { upload } from "@/api/modules/common";
import { Link as RouterLink } from 'react-router-dom'
import { listLog,getLog,delLog,addLog,updateLog} from "@/api/tool/log";
import { groupList,listDictionary,getDictionary,delDictionary,addDictionary,updateDictionary} from "@/api/tool/dictionary";
import useHistoryTags, {HistoryTag} from '@/store/modules/historyTags'
import useDynamicCache from '@/store/modules/dynamicCache'
import useCurrentPage from '@/store/modules/currentPage'
const { Step } = Steps;  
const { Option } = Select;  
const { TabPane } = Tabs; 

const logDetail = () => {  
  const { t } = useTranslation()
  const navigate = useNavigate();
  const currentPage = useCurrentPage()
  const [currentStep, setCurrentStep] = useState(0);  
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [form2] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState("");
  const [reportlist,setReportlist] = useState([]);
  const [screenlist,setScreenlist] = useState([]);
  const [remarkslist,setRemarkslist] = useState([]);
  const [isView, SetisView] = useState(false)
  const [formId,setFormId]  = useState(null)
  //子数据
  const [oldList,setoldList] = useState([])
  const [childList,setchildList] = useState([])  
  const [newList,setnewList] = useState([])
  //变更值
  const [originList,setoriginList] = useState([])  
  const [modifyList,setmodifyList] = useState([])
  const [finalList,setfinalList] = useState([]);
 // 创建refs来引用Card元素  
 const cardRef1 = useRef(null);  
 const cardRef2 = useRef(null);  
 const cardRef3 = useRef(null);  
 const cardRef4 = useRef(null); 
 const cardRef5 = useRef(null);  
 const cardRef6 = useRef(null);  
  const maodianlist = [  
    '摘要信息',  
    '原始的值',    
    '变更部分的值',  
    '最终的值',
    '子数据(修改前)',
    '子数据(修改后)',
  ];  

  const getQueryVariable = (variable) =>{
    const query = window.location.search.substring(1);
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
  }
  
  // 滚动到指定Card的函数  
  const scrollToCard = (cardRef) => {  
    if (cardRef && cardRef.current) {  
      // 滚动到目标Card的顶部位置  
      window.scrollTo({  
        top: cardRef.current.offsetTop - 70, // 减去一些值以考虑导航栏或顶部其他元素的高度  
        behavior: 'smooth', // 平滑滚动  
      });  
    }  
  };  

  // Steps的onChange事件处理函数  
  const handleStepChange = (nextStep) => {  
    setCurrentStep(nextStep);  
    // 根据步骤索引滚动到对应的Card  
    switch (nextStep) {  
      case 0:  
        scrollToCard(cardRef1);  
        break;  
      case 1:  
        scrollToCard(cardRef2);  
        break;  
      case 2:  
        scrollToCard(cardRef3);  
        break;  
      case 3:  
        scrollToCard(cardRef4);  
        break;  
      case 4:  
        scrollToCard(cardRef5);  
        break;  
      case 5:  
        scrollToCard(cardRef6);  
        break;  
      default:  
        break;  
    }  
  };  

  const columns: any = [
    {
      title: t('log.menu'),
      dataIndex: 'menu',
      key: 'menu',
      width: 80,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (menu) => (
        <Tooltip placement="topLeft" title={menu}>
          {menu}
        </Tooltip>
      ),
    },
    {
      title: t('log.typeName'),
      dataIndex: 'typeName',
      width: 100,
      key: 'typeName',
      ellipsis: {
        showTitle: false,
      },
      render: (typeName) => (
        <Tooltip placement="topLeft" title={typeName}>
          {typeName}
        </Tooltip>
      ),
    },
    {
      title: t('log.source'),
      dataIndex: 'source',
      width: 120,
      key: 'source',
      ellipsis: {
        showTitle: false,
      },
      render: (source) => (
        <Tooltip placement="topLeft" title={source}>
          {source}
        </Tooltip>
      ),
    },
    {
      title: t('log.searchValue'),
      dataIndex: 'searchValue',
      width: 80,
      key: 'searchValue',
      ellipsis: {
        showTitle: false,
      },
      render: (searchValue) => (
        <Tooltip placement="topLeft" title={searchValue}>
          {searchValue}
        </Tooltip>
      ),
    },
    {
      title: t('log.status'),
      dataIndex: 'status',
      width: 80,
      key: 'status',
      ellipsis: {
        showTitle: false,
      },
      render: (status) => (
        <Tooltip placement="topLeft" title={status}>
          {status}
        </Tooltip>
      ),
    },
    {
      title: t('log.operatorType'),
      dataIndex: 'operatorType',
      key: 'operatorType',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (operatorType) => (
        <Tooltip placement="topLeft" title={operatorType}>
          {operatorType}
        </Tooltip>
      ),
    },
    {
      title: t('log.createBy'),
      dataIndex: 'createBy',
      key: 'createBy',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (createBy) => (
        <Tooltip placement="topLeft" title={createBy}>
          {createBy}
        </Tooltip>
      ),
    },
    {
      title: t('log.createTime'),
      dataIndex: 'createTime',
      key: 'createTime',
      width:100,
      ellipsis: {
        showTitle: false,
      },
      render: (createTime) => (
        <Tooltip placement="topLeft" title={createTime}>
          {createTime}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      width:80,
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
        </>  
      ),  
    },  
  ];

  const handleView = (record) =>{
    let row = record
    let dictList=[]
    const query =  {
      pageNum:1,
      pageSize:9999,
      type:row.type,
     }
    listDictionary(query).then(res=>{
      let arr = []
      dictList=res.data.rows
      dictList.map(k=>{
        if(row.finalVlaue !==null){
            row.finalVlaue=row.finalVlaue.replace(k.oriName,k.nameCn);
            let data=JSON.parse(row.finalVlaue)
            for (const key in data){
              if(key==k.nameCn){
                  arr.push({ key: key,value:data[key]});
              }
            }
        }
      })
      setchildList(arr)
      setIsModalVisible(true)
    })
  }

  const getFileLink = (filename) =>{  
    // 这里返回一个文件链接的字符串，你可以根据需要进行修改  
    return `/res-dir/Articel/Original/${filename}`;  
  }  

   // 初始化数据  
   useEffect(() => {  
    getData() 
  }, []);  

  const getData = async () => {
    const id  =  getQueryVariable("id")
    if(id == 'null' ||id == "" || id ==undefined || id ==null){
    //
        
    }else{
        setFormId(id)
        getLog(id).then(res1=>{
            let data = res1.data.data
            form.setFieldsValue(res1.data.data)
            if(data.childList.length>0){
              data.childList.map(item=>{
                const query = {  pageNum:1,
                  pageSize:9999,
                  type:item.type,}
                  groupList(query).then(res=>{
                    let typelist =res.data.rows
                    let final = JSON.parse(item.finalVlaue)
                    typelist.map(k=>{
                            if(item.type==k.type){
                               let data= ""
                               k.dataDictionaryList.map(d=>{
                                  if(d.keyField=="Y"){
                                     for (const key in final) {
                                        if(key == d.oriName){
                                           data+=d.nameCn+':'+final[key]+','
                                        }
                                     }
                                  }
                               })
                               if(data.length>0){
                                  data=data.substring(0, data.length - 1)
                               }
                               item.searchValue=data
                            }
                         })
                  })
                })
                let newoldList = []
                let newnewList = []
                data.childList.map(i=>{
                  if(i.status=="new"){
                    newnewList.push(i)
                  }else if(i.status == "old"){
                    newoldList.push(i)
                  }
                })
                setoldList(newoldList)
                setnewList(newnewList)
              }

        //dictionary
        const query2 = {  pageNum:1,
          pageSize:9999,
          type:data.type}
        listDictionary(query2).then(res=>{
            console.log(res.data)
            let data2 = res.data.rows
            let arr =[]
            let arr1 =[]
            let arr2 =[]
            data2.map(k=>{
                if(data.originalValue !==null){
                  data.originalValue=data.originalValue.replace(k.oriName,k.nameCn);
                  let data5=JSON.parse(data.originalValue)
                  for (const key in data5){
                    if(key==k.nameCn){
                      arr.push({ key: key,value:data5[key]});
                    }
                  }
                }
                if(data.modifiedValue !==null){
                  data.modifiedValue=data.modifiedValue.replace(k.oriName,k.nameCn);
                  let data3=JSON.parse(data.modifiedValue)
                  for (const key in data3){
                    if(key==k.nameCn){
                      arr1.push({ key: key,value:data3[key]});
                    }
                  }
                }
                if(data.finalVlaue !==null){
                    data.finalVlaue=data.finalVlaue.replace(k.oriName,k.nameCn);
                    let data4=JSON.parse(data.finalVlaue)
                    for (const key in data4){
                      if(key==k.nameCn){
                        arr2.push({ key: key,value:data4[key]});
                      }
                    }
                }
               
            })
            setoriginList(arr)
            setmodifyList(arr1)
            setfinalList(arr2)
        })
      })
    }
  } 

  const historyTags = useHistoryTags()
  const cache = useDynamicCache()

  const submitFormCancel = () =>{
    console.log(currentPage,'currentPage')
    const data = historyTags.routeDelTags(currentPage.currentName);
    cache.reset(currentPage.currentName);
    if(data) navigate(data.path)
  }

  const CustomTitleWithButton = ({ title, onClick }) => (  
    <div style={{ display: 'flex', alignItems: 'center' }}>  
      <span>{title}</span>  
      <Button style={{ marginLeft: '8px' }} onClick={submitFormCancel}>  
        {t('cancel')}  
      </Button>  
    </div>  
  ); 


  
  return (  
    <div>  
      <Row justify="space-between" align="top">  
        <Col span={5} style={{ position: 'relative' }}>  
        <div  
            style={{ 
              width:'180px', 
              position: 'fixed',  
              top:90, // 从顶部开始粘住  
              zIndex: 1, // 确保在其他内容之上  
              backgroundColor: 'white',  
              padding: '10px', // 可选内边距  
              // 可以添加maxHeight和overflowY来处理内容过多时的情况  
            }}  
          >  
          <Steps direction="vertical" current={currentStep} onChange={handleStepChange}>  
            {maodianlist.map((item, index) => (  
              <Step  key={index} title={item} />  
            ))}  
          </Steps>  
          </div>
        </Col>  
        <Col span={19}>  
          {/* 第一个Card：表单 */}  
          <Card ref={cardRef1} title={  
          <CustomTitleWithButton  
            title={maodianlist[0]}  
            onClick={submitFormCancel}  
        />  
        }>  
             <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="menu"  
              label={t('log.menu')}
            >  
              <Input disabled/>  
            </Form.Item>
            <Form.Item  
              name="type"  
              label={t('log.type')}
            >  
              <Input disabled/>  
            </Form.Item>
            <Form.Item  
              name="typeName"  
              label={t('log.typeName')}
            >  
              <Input disabled/>  
            </Form.Item>
            <Form.Item  
              name="source"  
              label={t('log.source')}
            >  
              <Input disabled/>  
            </Form.Item>
            <Form.Item  
              name="operatorType"  
              label={t('log.operatorType')}
            >  
              <Input disabled/>  
            </Form.Item>
            <Form.Item  
              name="createBy"  
              label={t('log.createBy')}
            >  
              <Input disabled/>  
            </Form.Item>
            <Form.Item  
              name="createTime"  
              label={t('log.createTime')}
            >  
              <Input disabled/>  
            </Form.Item>
           </Form>  
          </Card>  
          {/* 第二个Card：表格 */}  
          <Card title={maodianlist[1]} ref={cardRef2} style={{marginTop:'2%'}}>
          <Form layout="vertical">  
            {originList.map((item, index) => (  
              <Form.Item  
                key={index} // 使用 index 作为 key，但通常建议使用唯一且稳定的值  
                label={item.key}  
                // 注意：Ant Design 的 Form.Item 不使用 prop 属性来绑定值，而是使用表单实例和 name 属性  
              >  
                 <Input value={item.value} disabled />
              </Form.Item>  
            ))} 
          </Form> 
          </Card>  
          {/* 第三个Card：表格（和第二个类似，但可能数据不同） */}  
          <Card title={maodianlist[2]} ref={cardRef3} style={{marginTop:'2%'}}> 
          <Form layout="vertical">  
            {modifyList.map((item, index) => (  
              <Form.Item  
                key={index} // 使用 index 作为 key，但通常建议使用唯一且稳定的值  
                label={item.key}  
                // 注意：Ant Design 的 Form.Item 不使用 prop 属性来绑定值，而是使用表单实例和 name 属性  
              >  
                 <Input value={item.value} disabled />
              </Form.Item>  
            ))} 
          </Form> 
          </Card>  
          {/* 第四个Card：文字内容 */}  
          <Card title={maodianlist[3]} ref={cardRef4} style={{marginTop:'2%'}}>
          <Form layout="vertical">  
            {finalList.map((item, index) => (  
              <Form.Item  
                key={index} // 使用 index 作为 key，但通常建议使用唯一且稳定的值  
                label={item.key}  
                // 注意：Ant Design 的 Form.Item 不使用 prop 属性来绑定值，而是使用表单实例和 name 属性  
              >  
                 <Input value={item.value} disabled />
              </Form.Item>  
            ))} 
          </Form>  
          </Card> 
           {/* 第五个Card：文字内容 */}  
           <Card title={maodianlist[4]} ref={cardRef5} style={{marginTop:'2%'}}>
           <Table  
                  dataSource={oldList} // 筛选与 subjectLevel 匹配的数据  
                  columns={columns}  
                  rowKey={(record) => record.id} // 假设每条记录都有一个唯一的id  
                  pagination={false}
                  bordered  
                  scroll={{ x: '1100px' }} // 或者使用具体的像素值，如 '1000px' 
                /> 
            
          </Card> 
            {/* 第六个Card：文字内容 */}  
            <Card title={maodianlist[4]} ref={cardRef6} style={{marginTop:'2%'}}>
           <Table  
                  dataSource={newList} // 筛选与 subjectLevel 匹配的数据  
                  columns={columns}  
                  rowKey={(record) => record.id} // 假设每条记录都有一个唯一的id  
                  pagination={false}
                  bordered  
                  scroll={{ x: '1100px' }} // 或者使用具体的像素值，如 '1000px' 
                /> 
            
          </Card> 
          {/* 在这里放置保存按钮 */}  
          <div style={{ textAlign: 'left', marginTop: '16px' }}>  
                 
                <Button  onClick={() => { submitFormCancel() }}>  
                  {t('cancel')}  
                </Button> 
           </div>     
        </Col>  
      </Row> 
      <Modal  
        title='查看/View'  
        visible={isModalVisible}  
        onCancel={()=>setIsModalVisible(false)}  
        footer={[  
          <Button key="back" onClick={()=>setIsModalVisible(false)}>  
            取消  
          </Button>,  
        ]}  
        destroyOnClose
      >  
         <Form layout="vertical">  
            {childList.map((item, index) => (  
              <Form.Item  
                key={index} // 使用 index 作为 key，但通常建议使用唯一且稳定的值  
                label={item.key}  
                // 注意：Ant Design 的 Form.Item 不使用 prop 属性来绑定值，而是使用表单实例和 name 属性  
              >  
                 <Input.TextArea value={item.value} disabled />
              </Form.Item>  
            ))} 
          </Form> 
      </Modal> 

    </div>  
  );  
};  
  
export default logDetail;